# -*- coding:utf-8 -*-
# @Time : 2020/10/15 19:32
# @Author: limeng
# @File : views.py
from . import plan_task
from ...apps.plan_task.service import task_service
from flask import request
from ...libs import const
from ...libs.framework import *
from ...libs.validate_params import validate_params


@plan_task.route('/sel_task', methods=['post'])
@validate_params(params=["page_num", "page_per"])
def sel_task():
    """
    自动任务(查询)
    :return: json
    """
    res = task_service.sel_task(request.json)
    return result(const.SUCCESS, None, res)


@plan_task.route('/task_upload', methods=['post'])
# @validate_params(params=["file", "user_id"])
def task_upload():
    """
    脚本上传
    :return: json
    """
    f = request.files["file"]
    user_id = request.form["user_id"]
    res = task_service.file_upload(f, user_id)
    if res:
        res_json = result(const.SUCCESS, const.UPLOAD_FILE_SUCCESS, None)
    else:
        res_json = result(const.FAIL_50000, const.UPLOAD_FILE_FAIL, None)
    return res_json


@plan_task.route('/insert_task', methods=['post'])
@validate_params(params=["task_name", "cron", "user_id"])
def insert_task():
    """
    添加脚本 INSERT_FAIL
    :return: json
    """
    res = task_service.add_qa_task(request.json)
    if res:
        res_json = result(const.SUCCESS, const.INSERT_SUCCESS, None)
    else:
        res_json = result(const.FAIL_50000, const.INSERT_FAIL, None)
    return res_json


@plan_task.route('/del_task', methods=['post'])
@validate_params(params=["task_id", "user_id"])
def del_task():
    """
    删除脚本
    :return: json
    """
    res = task_service.del_task(request.json)
    if res:
        res_json = result(const.SUCCESS, const.DELETE_SUCCESS, None)
    else:
        res_json = result(const.FAIL_50000, const.DELETE_FAIL, None)
    return res_json


@plan_task.route('/edit_task', methods=['post'])
@validate_params(params=["task_name", "user_id", "id", "user_id"])
def ed_task():
    """
    修改脚本
    :return: json
    """
    res = task_service.edit_task(request.json)
    if res:
        res_json = result(const.SUCCESS, const.EDIT_SUCCESS, None)
    else:
        res_json = result(const.FAIL_50000, const.EDIT_FAIL, None)
    return res_json


@plan_task.route('/run_stop', methods=['post'])
@validate_params(params=["status", "task_id", "user_id"])
def run_stop():
    """
    启动、停止任务
    :return: json
    """
    return task_service.run_stop_task(request.json)


@plan_task.route('/task_run', methods=['post'])
@validate_params(params=["task_id", "user_id"])
def task_run():
    """
    执行
    :return: json
    """
    return task_service.task_run(request.json)


@plan_task.route('/sel_tasklog', methods=['post'])
@validate_params(params=["id", "page_num", "page_per"])
def sel_tasklog():
    """
    查询日志
    :return: json
    """
    res = task_service.sel_tasklog(request.json)
    return result(const.SUCCESS, None, res)
